const Db = require('./db')
const vk = require('./vk')

class pic
{
  static async list(ctx){
    let params = ctx.query
    let page = params.page
    let limit = params.limit
    let start = page>1?limit*(page - 1):0;
    let classId = params.class?params.class:'';
    if(typeof(page) != "number"){page = parseInt(page)}
    if(typeof(limit) != "number"){limit = parseInt(limit)}
    let data = {
      sql:"SELECT * FROM vk_pic_list WHERE class = CASE WHEN ? != '' THEN ? ELSE class END ORDER BY id DESC LIMIT ?,?",
      values:[classId,classId,start,limit]
    }
    let [err,res] = await Db.query(data)
    if(err){return ctx.body = vk.showData(500,err,"请求失败")}
    let data2 = {
      sql:"SELECT COUNT(id) AS count FROM vk_pic_list WHERE class = CASE WHEN ? != '' THEN ? ELSE class END",
      values:[classId,classId]
    }
    let [err2,res2] = await Db.query(data2)
    let r = {
      list:res,
      count:res2[0].count
    }
    ctx.body = vk.showData(200,r,'ok')
  }

  static async edit(ctx){
    let params = ctx.request.body
    let data = {
      sql:"UPDATE vk_pic_list SET class = ? WHERE id = ?",
      values:[params.class,params.id]
    }
    let [err,res] = await Db.query(data)
    if(err){return ctx.body = vk.showData(500,err,"请求失败")}
    ctx.body = vk.showData(200,res,'ok')
  }

  static async del(ctx){
    let params = ctx.request.body
    let data = {
      sql:"DELETE FROM vk_pic_list WHERE id = ?",
      values:[params.id]
    }
    let [err,res] = await Db.query(data)
    if(err){return ctx.body = vk.showData(500,err,"请求失败")}
    ctx.body = vk.showData(200,res,'ok')
  }

  static async classList(ctx){
    let data = {
      sql:"SELECT * FROM vk_pic_class"
    }
    let [err,res] = await Db.query(data)
    if(err){return ctx.body = vk.showData(500,err,"请求失败")}
    ctx.body = vk.showData(200,res,'ok')
  }

  static async classAdd(ctx){
    let params = await ctx.request.body
    let data = {
      sql:"INSERT INTO vk_pic_class (title,pid) VALUES (?,?)",
      values:[params.title,params.pid]
    }
    let [err,res] = await Db.query(data)
    if(err){return ctx.body = vk.showData(500,err,"请求失败")}
    ctx.body = vk.showData(200,res,'ok')
  }
}

module.exports = pic